package com.map.modules.controller;

import com.map.components.https.RequestEntity;
import com.map.components.https.SSLClient;
import com.map.core.consts.CommonConsts;
import com.map.core.utils.JsonUtils;
import com.map.core.utils.StringUtils;
import com.map.core.vo.ReturnEnum;
import com.map.core.vo.VoMsgHelper;
import com.map.modules.entity.Job;
import com.map.modules.entity.JobEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import java.util.Properties;

@Slf4j
@RestController
@RequestMapping(value = "/getConfig")
public class ConfigController {

    @RequestMapping(value = "/addJob", method = RequestMethod.POST)
//    public String createPdfReportByTemplate(@RequestBody JobEntity jobEntity){
    public String addJob(@RequestParam String params){
        try {
            //先告知对方自己状态是工作中
            JobEntity jobEntity = JsonUtils.jsonToPojo(params, JobEntity.class);
            setStatus("working");
            List<Job> jobList = jobEntity.getJobList();
            for (Job job : jobList) {
                dealJob(job);
            }
        }catch (Exception e) {
            e.printStackTrace();
            return VoMsgHelper.constJsonMsg(null, ReturnEnum.FAIL);
        }
        //告知对方自己状态是空闲
        setStatus("free");
        return VoMsgHelper.constJsonMsg(null, ReturnEnum.SUCCESS);
    }

    /**
     * 处理每个job，下载图片、验证图片、存图;最多执行三次，三次还没有存图，发送失败请求
     * @param job
     */
    private void dealJob(Job job){
        //错误job标志
        boolean isErrorJob = true;
        // 图片保存路径
        String temImgPath = CommonConsts.UPLOAD_IMG_PATH + job.getPath();

        //文件夹不存在，就先创建文件夹
        File tempDir = new File(temImgPath);
        if (!tempDir.exists()) {
            tempDir.mkdirs();
        }
        temImgPath += job.getImg();
        File file = new File(temImgPath);
        for(int i=0; i<3 ; i++){
            // 下载图片
            downloadPicture(job.getUrl(),file);
            // 校验图片有效性,有效则保留图,并退出循环
            if(checkImg(file)){
                isErrorJob = false;
                break;
            }else{
                file.delete();
            }
        }
        // 三次还没存图成功，发送失败请求
        if(isErrorJob){
            String url = getUrl();
            if(StringUtils.isEmpty(url)){
                log.error("url is empty!");
            }else{
                url += "api/errorJob";
                sendMessage(url, JsonUtils.objectToJson(job));
            }
        }
    }

    /**
     * 验证图片有效性
     * @param file
     */
    private static boolean checkImg(File file){
        try{
            BufferedImage bufferedImage = ImageIO.read(file);
            if(bufferedImage != null){
                return true;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 链接url下载图片,存放到临时目录
     * @param urlList
     * @param file
     */
    private static void downloadPicture(String urlList,File file) {
        URL url = null;
        try {
            url = new URL(urlList);
            DataInputStream dataInputStream = new DataInputStream(url.openStream());

            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;

            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            BASE64Encoder encoder = new BASE64Encoder();
            String encode = encoder.encode(buffer);//返回Base64编码过的字节数组字符串
            System.out.println(encode);
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 告知彼放自己的状态（空闲：free，工作中：working）
     */
    public static void setStatus(String worker) {
        try{
            String url = getUrl();
            if(StringUtils.isEmpty(url)){
                log.error("url is empty!");
            }else{
                url += "api/status";
                CommonConsts.jarWork = worker;
                sendMessage(url, worker);
            }
            log.info("url--"+ url + " : send status free!");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    private static void sendMessage(String url,String params){
        RequestEntity request = new RequestEntity();
        request.setUrl(url);
        request.setParam("params",params);
        SSLClient.post(request);
    }

    /**
     * 获取配置文件中的值
     * @return
     */
    public static String getUrl() {
       return getConfigProperties("baidumap.url");
    }

    private static String getConfigProperties(String name) {
        File file = new File("");
        try {
            String filePath = file.getCanonicalPath() + "/mapconfig.properties";
            Properties properties = new Properties();
            try {
                properties.load(new FileInputStream(filePath));
                return properties.getProperty(name);
            } catch (FileNotFoundException e) {
                log.error("找不到配置文件 mapconfig.properties",e);
                return VoMsgHelper.constJsonMsg(null, ReturnEnum.ERROR_10014);
            } catch (IOException e) {
                log.error("读取配置文件 mapconfig.properties失败",e);
                return VoMsgHelper.constJsonMsg(null, ReturnEnum.UNKNOW_ERROR);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(file!=null){
                file.delete();
            }
        }
        return null;
    }
    /**
     * 是windwo还是linux环境
     * @return
     */
    public static boolean isOSLinux() {
        Properties prop = System.getProperties();
        String os = prop.getProperty("os.name");
        if (os != null && os.toLowerCase().indexOf("linux") > -1) {
            return true;
        } else {
            return false;
        }
    }
}
